import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:pet/app/routes/app_pages.dart';
import 'package:pet/app/websocket_controller.dart';
import 'package:pet/env.dart';
import 'package:sensors_plus/sensors_plus.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'dart:math';
import 'package:local_auth/local_auth.dart';
import 'package:local_auth_android/local_auth_android.dart';

import '../../../storage/token.dart';

class LoginController extends GetxController {
  var username = ''.obs;

  var password = ''.obs;

  /// 是否同意协议
  RxBool agree = false.obs;

  // 是否隐藏密码
  RxBool hidden = true.obs;

  bool canCheckBiometrics = false;

  List<double>? _userAccelerometerValues;
  List<double>? _accelerometerValues;
  List<double>? _gyroscopeValues;
  List<double>? _magnetometerValues;

  final _streamSubscriptions = <StreamSubscription<dynamic>>[];
  final LocalAuthentication auth = LocalAuthentication();

  @override
  void onInit() async {
    super.onInit();
    await permissionNotification();
    await checkBiometrics();
    _streamSubscriptions.add(
      userAccelerometerEvents.listen(
        (UserAccelerometerEvent event) {
          if (event.x > 20) {
            _userAccelerometerValues = <double>[event.x, event.y, event.z];
            setEnv();
            Get.snackbar("环境切换", config().wss);
            WebsocketController websocketController =
                Get.find<WebsocketController>();
            websocketController.closeWebsocket();
            websocketController.connect();
          }
        },
        onError: (e) {
          print(e);
        },
        cancelOnError: true,
      ),
    );
    _streamSubscriptions.add(
      accelerometerEvents.listen(
        (AccelerometerEvent event) {
          _accelerometerValues = <double>[event.x, event.y, event.z];
        },
        onError: (e) {
          print(e);
        },
        cancelOnError: true,
      ),
    );
    _streamSubscriptions.add(
      gyroscopeEvents.listen(
        (GyroscopeEvent event) {
          _gyroscopeValues = <double>[event.x, event.y, event.z];
        },
        onError: (e) {
          print(e);
        },
        cancelOnError: true,
      ),
    );
    _streamSubscriptions.add(
      magnetometerEvents.listen(
        (MagnetometerEvent event) {
          _magnetometerValues = <double>[event.x, event.y, event.z];
        },
        onError: (e) {
          print(e);
        },
        cancelOnError: true,
      ),
    );
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
    for (final subscription in _streamSubscriptions) {
      subscription.cancel();
    }
  }

  setUsername(String inputUsername) {
    username.value = inputUsername;
  }

  setPassword(String inputPassword) {
    password.value = inputPassword;
  }

  changeStatusPassword() {
    hidden.value = !hidden.value;
  }

  permissionNotification() async {
    if (!await Permission.notification.isGranted) {
      openAppSettings();
    }
  }

  toLoginPage() {
    TokenStorage tokenStorage = Get.find<TokenStorage>();
    tokenStorage.deletePassword();
    tokenStorage.deleteUsername();
    Get.offAllNamed(Routes.LOGIN);
  }

  login() {
    WebsocketController websocketController = Get.find<WebsocketController>();

    websocketController.getToken(username.value, password.value);
  }

  Future<void> fingerprintlogin() async {
    bool authenticated = false;
    AndroidAuthMessages androidAuthMessages = const AndroidAuthMessages(
      biometricHint:"验证身份",
      cancelButton: '取消',
      goToSettingsButton: '去设置',
      goToSettingsDescription: '请设置指纹.',
      signInTitle: '指纹验证',
      biometricSuccess:'验证成功',
      biometricNotRecognized:"验证失败",
    );
    try {
      authenticated = await auth.authenticate(
        localizedReason: '扫描指纹以进行身份验证',
        authMessages: [androidAuthMessages],
        options: const AuthenticationOptions(
          stickyAuth: true,
          biometricOnly: true,
        ),
      );
    } on PlatformException catch (e) {
      print(e);
    }

    if (authenticated) {
      // 用户已通过指纹验证
      TokenStorage tokenStorage = Get.find<TokenStorage>();
      WebsocketController websocketController = Get.find<WebsocketController>();
      String username = tokenStorage.getUsername();
      String password = tokenStorage.getPassword();

      websocketController.getToken(username, password);
    }
  }

  checkBiometrics() async {
    TokenStorage tokenStorage = Get.find<TokenStorage>();
    final bool canAuthenticateWithBiometrics = await auth.canCheckBiometrics;
    canCheckBiometrics = !tokenStorage.getUsername()?.isEmpty &&
        !tokenStorage.getPassword()?.isEmpty &&
        canAuthenticateWithBiometrics &&
        await auth.isDeviceSupported();
    update();
  }
}
